import { mapTwoLevelRouter } from '@/store/help'
import { App } from 'vue'
import { createRouter, createWebHashHistory } from 'vue-router'
import { constantRoutes, defaultPathRoute } from './routes/constants'
import { extraRoutes } from './routes/extra-routes'

const router = createRouter({
  history: createWebHashHistory(),
  routes: mapTwoLevelRouter([...constantRoutes, ...extraRoutes, defaultPathRoute]),
})

export default router

export function setupRouter(app: App) {
  app.use(router)

  // 编译环境下，控制刷新后跳转到首页
  if (import.meta.env.PROD) {
    window.addEventListener('pageshow', function () {
      // 检查 window.performance 是否存在
      if (window.performance) {
        // 获取导航性能条目
        const navigationEntries = performance.getEntriesByType('navigation')
        if (navigationEntries.length > 0) {
          const navEntry = navigationEntries[0]
          // 判断是否为页面刷新
          if (navEntry.type === 'reload') {
            // 如果是手动刷新，则跳转到首页
            window.location.href = '/'
          }
        }
      }
    })
  }
}
